<template>
  <div class="cost-table-container">
    <FilterInput v-if="!onlyView" v-model="paramsObj" :filter-list="filterList" class="FilterTool" line-feed show-search-btn @handelClick="queryClick" @queryEmpty="queryEmpty" />
    <div v-loading="listLoading" class="table-container">
      <div v-if="!onlyView" class="opeator-top">
        <div class="tip">请勾选需要提交结算的成本</div>
        <SelectionNum :select-item="multipleSelectionAll" @clearMixinSelection="clearAllCost" >
          <div>
            <span style="font-size: 14px; color: #666;">成本，结算金额 </span>
            <span v-if="totalPrice || totalPrice === 0" style="font-size: 14px; color: #406eff;font-weight:600;">{{ (totalPrice/100) | moneyFilter(true, '元', true) }}</span>
            <span v-else style="font-size: 14px; color: #406eff;">--</span>
          </div>
        </SelectionNum>
      </div>
      <el-table
        v-if="settleOrder.items.length > 0"
        ref="costTable"
        :data="settleOrder.items"
        :row-key="getRowKeys"
        :row-class-name="(data) => tableRowClassName(data, 'pointer')"
        element-loading-text="加载中..."
        empty-text="暂无数据"
        class="fb-table"
        header-cell-class-name="order-data-header-cell"
        fit
        hightlight-current-row
        @select="onSelectTable"
        @select-all="onSelectTable">
        <el-table-column
          align="center"
          fixed="left"
          type="selection"
          reserve-selction
          width="50"/>
        <el-table-column label="成本编号" align="left" min-width="180">
          <template slot-scope="scope">
            <el-tooltip v-if="scope.row.costNum" class="item" effect="dark" placement="top-start">
              <div slot="content" style="max-width: 200px;">{{ scope.row.costNum }}</div>
              <div class="ellipsisOne" style="color: #406EFF;cursor:pointer;" @click="toCostDetail(scope.row)">{{ scope.row.costNum }}</div>
            </el-tooltip>
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column label="成本项" align="left" min-width="130">
          <template slot-scope="scope">
            <el-tooltip v-if="scope.row.costItemName" class="item" placement="top-start" effect="dark">
              <div slot="content" style="max-width: 200px;">{{ scope.row.costItemName }}</div>
              <div class="ellipsisOne">{{ scope.row.costItemName }}</div>
            </el-tooltip>
            <div v-else>--</div>
          </template>
        </el-table-column>
        <el-table-column label="含税成本(元)" align="right" min-width="130">
          <template slot-scope="scope">
            <PriceColumn :real-val="scope.row.taxCost" :price="scope.row.taxCost / 100" />
          </template>
        </el-table-column>
        <el-table-column label="供应商" align="left" min-width="120">
          <template slot-scope="scope">
            <el-tooltip v-if="scope.row.supplierName" class="item" placement="top-start" effect="dark">
              <div slot="content" style="max-width: 200px;">{{ scope.row.supplierName }}</div>
              <div class="ellipsisOne">{{ scope.row.supplierName }}</div>
            </el-tooltip>
            <div v-else>--</div>
          </template>
        </el-table-column>
        <el-table-column label="说明" align="left" min-width="190">
          <template slot-scope="scope">
            <el-tooltip v-if="scope.row.costDescription" class="item" placement="top-start" effect="dark">
              <div slot="content" style="max-width: 200px;">{{ scope.row.costDescription }}</div>
              <div class="ellipsisOne">{{ scope.row.costDescription }}</div>
            </el-tooltip>
            <div v-else>--</div>
          </template>
        </el-table-column>
        <el-table-column label="成本来源" align="left" min-width="120">
          <template slot-scope="scope">
            <div>{{ scope.row.costBelong | costBelongFilter }}</div>
          </template>
        </el-table-column>
        <el-table-column label="成本类型" align="left" min-width="90">
          <template slot-scope="scope">
            <div>{{ scope.row.costType | costTypeFilter }}</div>
          </template>
        </el-table-column>
        <el-table-column align="left" label="审批状态" width="80">
          <template slot-scope="scope">
            <div v-if="scope.row.approvalStatus || scope.row.approvalStatus === 0" :style="{color: getColor(scope.row.approvalStatus)}">
              {{ scope.row.approvalStatus | costApprovalStatus }}
            </div>
            <div v-else>--</div>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="left" min-width="150">
          <template slot-scope="scope">
            <div>{{ scope.row.createDate | format('YYYY/MM/DD HH:mm') }}</div>
          </template>
        </el-table-column>
        <el-table-column label="创建人" align="left" min-width="100">
          <template slot-scope="scope">
            {{ scope.row.creator || '--' }}
          </template>
        </el-table-column>
      </el-table>
      <empty-placeholder v-else is-border mode="table" style="margin-bottom: 24px" />
      <div v-if="!onlyView" style="display: flex; justify-content: flex-end;">
        <el-pagination
          v-show="settleOrder.total > 0"
          :current-page="page"
          :page-size="perPage"
          :total="settleOrder.total"
          :page-sizes="[10, 20, 50, 100, 250, 500]"
          :layout="showMobilePage?'total, prev, next, jumper':'total, prev, pager, next, sizes, jumper'"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </div>
  </div>
</template>

<script>
import EmptyPlaceholder from '@/components/Common/emptyPlaceholder';
import { getCostList } from '@/api/costManage';
import { getDepartment } from '@/api/project';
import { costList } from '@/api/config';
import { moneyFilter } from '@/filters/number';
import { costBelongFilter, costTypeFilter, costApprovalStatus, setAccountState } from '@/filters/status';
import { format } from '@/filters/date';
import { costBelong, costType } from '@/views/cost/model/selectData';
import tableSelections from '@/mixins/tableSelections';
import costSet from '@/mixins/costSet';
import { paramsRangeFormat } from '@/utils/paramsFormat';
import { mapState } from 'vuex';

export default {
  components: { EmptyPlaceholder },
  filters: {
    moneyFilter,
    format,
    costBelongFilter,
    costTypeFilter,
    costApprovalStatus,
    setAccountState },
  mixins: [tableSelections, costSet],
  props: {
    costId: {
      type: String | Number | Array,
      default: ''
    },
    supplierId: {
      type: String | Number,
      default: ''
    },
    stepTwoData: {
      type: Object,
      default: null
    },
    onlyView: { // 仅显示不调用接口
      type: Boolean,
      default: false
    },
    isAddCost: { // 是否来子关联成本弹窗
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      page: 1,
      perPage: 10,
      selectData: [],
      paramsObj: {},
      listLoading: false,
      settleOrder: {
        items: [],
        total: 0
      },
      tableRefName: 'costTable', // 表格的ref名称
      idKey: 'id', // 唯一表示字段
      costItem: [],
      departmentOption: [],
      // 获取row的key值
      getRowKeys(row) {
        return row.id;
      },

      costItemId: null, // 成本项ID
      costOrderId: null, // 成本ID  对应订单列表中的 orderCostItemId
      relatedOrderId: null // 关联订单ID
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    }),
    filterList() {
      const arr = [
        // 输入框
        { keyword: 'costNum', name: '成本编号', placeholder: '支持批量搜索，以","隔开即可', type: 'input', inputType: 'textarea', maxlength: 2000, maxLength: 2000, lengthLimit: true },
        { keyword: 'costDescription', name: '说明', type: 'input' },
        { keyword: 'creator', name: '创建人', type: 'input' },
        // 下拉
        { keyword: 'departmentId', name: '所属部门', type: 'select', isSearch: true, options: this.departmentOption }, // 可搜索下拉
        { keyword: 'costBelong', name: '成本来源', type: 'select', options: costBelong },
        { keyword: 'costType', name: '成本类型', type: 'select', options: costType },
        // 日期
        { keyword: 'createTime', name: '创建时间', timeType: 'daterange', type: 'rangeDate' }
      ];
      return arr;
    },
    totalPrice() {
      let totalPrice = 0;
      this.selectData.forEach((i) => {
        totalPrice += i.costPrice ? i.costPrice : i.taxCost;
      });
      return totalPrice;
    }
  },
  watch: {
    costId() {
      this.getCostList(true);
    }
  },
  created() {
    // 从成本列表结算而来才会有下面2个属性，用于自动选择成本或订单
    this.costItemId = Number(this.$route.query.costItemId) || null; // 成本项ID
    this.costOrderId = Number(this.$route.query.costId) || null; // 成本ID
    this.relatedOrderId = Number(this.$route.query.relatedOrderId) || null; // 关联订单ID

    if (!this.onlyView) {
      this.getCostList();
      this.getDepartmentData();
      this.getCostItemList();
    }
  },
  methods: {
    // 新窗口打开成本详情页
    toCostDetail(data) {
      const url = this.$router.resolve({
        name: 'costDetail',
        params: { id: data.id }
      });
      window.open(url.href, '_blank');
    },
    getCostList(reset = false) {
      if (this.onlyView) return;
      const costItemId = this.costItemId || (Array.isArray(this.costId) ? this.costId.join() : this.costId);
      if (!costItemId) {
        this.settleOrder = {
          items: [],
          total: 0
        };
        return;
      }
      if (reset) this.page = 1;
      const params = JSON.parse(JSON.stringify(this.paramsObj));
      params.page = this.page;
      params.perPage = this.perPage;
      params.supplierId = this.supplierId;
      params.costItemId = costItemId;
      params.isNotRelateOrder = 0;
      params.settlementStatus = 0;
      if (this.$route.query.settleId && !this.isAddCost) {
        params.settleId = this.$route.query.settleId;
      }
      paramsRangeFormat([{ attr: 'createTime', start: 'createDateStart', end: 'createDateEnd',
        type: 'time', dayEnd: true
      }], params);
      const AllSelectedCost = this.stepTwoData.cost || [];
      this.listLoading = true;
      getCostList(params).then(res => {
        this.listLoading = false;
        if (res.code === 200) {
          this.settleOrder = res.data;
          this.selectFun(res.data.items, AllSelectedCost);
          if (this.setSelectRow) this.setSelectRow(res.data.items);
          if (res.data.otherData.differenceSn) {
            this.$message({
              dangerouslyUseHTMLString: true,
              type: 'warning',
              message: `<div>编号${res.data.otherData.differenceSn.join('<br>')}的订单/成本不存在或无权限或状态为结算中/结算完成</div>`
            });
          }
        }
      }).catch(e => {
        this.listLoading = false;
      });
    },
    queryClick() {
      this.getCostList(true);
    },
    queryEmpty() {
      this.paramsObj = {};
      if (this.clearMixinSelection) this.clearMixinSelection();
      this.getCostList(true);
    },
    onSelectTable(selection, row) {
      this.onlyView ? this.$emit('costSelectedReset', selection) : this.selectTable(selection, row);
    },
    clearAllCost() {
      this.clearMixinSelection();
      this.$nextTick(() => {
        this.$emit('costSelectedReset', []);
      });
    },
    // 选中订单
    tableSelectionChange(e) {
      this.selectData = e;
      this.$emit('selectData', this.multipleSelectionAll);
    },
    handleSizeChange(val) {
      this.perPage = val;
      this.getCostList(true);
    },
    handleCurrentChange(val) {
      this.page = val;
      this.getCostList();
    },

    // 获取成本管理下包含的部门
    getDepartmentData() {
      const params = {
        type: 6
      };
      getDepartment(params).then(res => {
        if (res.data) {
          res.data.unshift({ value: -2, label: '--' });
          this.departmentOption = res.data;
        }
      });
    },
    // 获取成本项列表
    getCostItemList() {
      costList().then(res => {
        if (res.data) {
          const costItem = res.data.items;
          costItem.forEach(item => {
            item.value = item.costId;
            item.label = item.costName;
          });
          this.costItem = costItem;
        }
      });
    },
    selectFun(list, AllSelectedCost = []) { // 回填选择列表
      const relatedOrderId = this.relatedOrderId;
      const costOrderId = this.costOrderId;
      const setData = new Set(); // 去重
      let selectAllIds = this.multipleSelectionAll.map(row => row.id);
      if (!relatedOrderId && costOrderId) setData.add(costOrderId); // 没有关联id,且有costOrderId 才可以选中成本
      // 从下一步返回回来后需要 取出 stepTwoData的数据进行回填
      if (AllSelectedCost.length) {
        if (Array.isArray(this.costId)) {
          const allCostList = [];
          AllSelectedCost.forEach(cost => {
            allCostList.push(...cost.orderCostItemIds);
          });
          this.multipleSelectionAll = allCostList;
          this.$emit('costSelectedReset', allCostList);
          this.$nextTick(() => {
            this.stepTwoData.cost = [];
          });
        } else {
          const currentCost = AllSelectedCost.find(i => i.costId === this.costId);
          if (currentCost && currentCost.orderCostItemIds && currentCost.orderCostItemIds.length) {
            currentCost.orderCostItemIds.forEach(i => {
              if (!i.id) i.id = i.orderCostItemId;
            });
            const cacheSelectCost = currentCost.orderCostItemIds.filter(i => {
              if (!selectAllIds.includes(i.id)) setData.add(i.id);
              return !selectAllIds.includes(i.id);
            });
            this.multipleSelectionAll = this.multipleSelectionAll.concat(cacheSelectCost);
          }
        }
      }
      this.tableSelectionChange(this.multipleSelectionAll);
      let ids = [...setData];

      selectAllIds = this.multipleSelectionAll.map(row => row.id);
      ids = ids.filter(i => { return !selectAllIds.includes(i); }); // 排除已经被选中的
      if (ids.length > 0) {
        this.$nextTick(() => {
          for (var i = 0; i < list.length; i++) {
            if (ids.includes(list[i].id)) {
              this.multipleSelectionAll.push(list[i]);
              this.tableSelectionChange(this.multipleSelectionAll);
            }
          }
        });
      }
    },
    parseObj(str) {
      try {
        return JSON.parse(str);
      } catch (error) {
        return [];
      }
    },
    // 勾选状态重置
    resetSelectStatus() {
      this.$nextTick(() => {
        const selectedIds = this.multipleSelectionAll.map(i => i.id);
        this.settleOrder.items.forEach(row => {
          this.$refs['costTable'].toggleRowSelection(row, selectedIds.includes(row.id));
        });
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.table-container {
  .opeator-top {
    display: flex;
    margin: 6px 0;
    height: 32px;
    align-items: center;
    @include scrollBar($x: auto, $y: hidden, $width: 6px);
  }
  .tip {
    color: #999;
    font-size: 13px;
    margin-right:20px;
    white-space: nowrap;
  }
}
.FilterTool {
  margin-top: 12px;
  &::v-deep {
    .el-date-editor {
      &.el-input__inner {
        width: 240px !important;
      }
    }
  }
}
</style>
